package com.tunan.system.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.EasyUiPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tunan.common.PagePermissionUtil;
import com.tunan.common.Result;
import com.tunan.common.resultSub.ResultFailure;
import com.tunan.common.resultSub.ResultSuccess;
import com.tunan.persistence.model.TSysRole;
import com.tunan.persistence.model.TSysRoleLink;
import com.tunan.persistence.model.TSysUser;
import com.tunan.system.service.IdentifierGenerator;
import com.tunan.system.service.SysRoleLinkService;
import com.tunan.system.service.SysRoleService;
import com.tunan.system.service.SysUserService;

@Controller
@RequestMapping(value = "SysRole")
public class SysRoleController extends BaseController {
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private IdentifierGenerator identifierGenerator;
	
	@Autowired
	private SysRoleLinkService roleLinkService;

	@Autowired
	private SysUserService userService;
	
	private Logger log = Logger.getLogger(SysRoleController.class);
	
	

	@RequestMapping(value = "addRole", method = RequestMethod.GET)
	public ModelAndView addRole(String id, HttpServletRequest request) {
		if (StringUtils.isNotBlank(id)) {
			TSysRole role = sysRoleService.selectOne(id);
			List<TSysUser> userList = userService.findUserByRoleId(id);
			if(userList != null && userList.size() > 0){
				String uids = "";
				String names = "";
				for(TSysUser user : userList){
					String czyid = user.getCzyid();
					if(StringUtils.isNotBlank(uids) && StringUtils.isNotBlank(names)){
						uids += "," + czyid ;
					    names += "," + user.getXm();
					}else{
						uids += czyid;
						names += user.getXm();
					}
				}
				role.setUids(uids);
				role.setNames(names);
			}
			request.setAttribute("vo", role);
		}
		return new ModelAndView("/system/addRole");
	}

	@RequestMapping(value = "sysRoleList", method = RequestMethod.GET)
	public ModelAndView sysRoleList(String menuId, HttpServletRequest request) {
		if(StringUtils.isNotBlank(menuId)){
			request.setAttribute("pagePermission", PagePermissionUtil.getPRight(menuId, request.getSession()));
		}
		return new ModelAndView("/system/sysRoleList");
	}

	/**
	 * 查询角色
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "queryAll", method = RequestMethod.POST)
	@ResponseBody
	public EasyUiPage list(@ModelAttribute("pageParams") Page pageParams,
			TSysUser params) {
		PageHelper.startPage(pageParams.getPageNum(), pageParams.getPageSize());
		Page pageresult = (Page) sysRoleService.findAll();
		return pageresult.getEasyUiPage();
	}

	/**
	 * 新增和修改
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Result save(@ModelAttribute("role") TSysRole role) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			if (role != null) {
				if (StringUtils.isNotBlank(role.getId())) {
					sysRoleService.update(role);
					// 重新选择以后就需要保存
					roleLinkService.delete(role.getId());
					saveTSysRoleLink(role);
					rs.setMessage("修改成功");
				} else {
					role.setId(identifierGenerator.generate());
					sysRoleService.insertSelective(role);
					saveTSysRoleLink(role);
					rs.setMessage("新增成功");
				}

			}
			return rs;

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("操作失败");
		return rf;
	}
	
	
	private void saveTSysRoleLink(TSysRole role){
		if (StringUtils.isNotBlank(role.getUids())) {
			String[] str = role.getUids().split(",");
			for (int i = 0; i < str.length; i++) {
				TSysRoleLink roleLink = new TSysRoleLink();
				roleLink.setYwlsh(identifierGenerator.generate());
				roleLink.setCzyid(str[i]);
				roleLink.setRoleid(role.getId());
				roleLinkService.insert(roleLink);
			}
		}
	}

	/**
	 * 删除
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Result delete(String id) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			if (StringUtils.isNotBlank(id)) {
				sysRoleService.delete(id);
				roleLinkService.delete(id);
			}
			rs.setMessage("删除成功");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("删除失败");
		return rf;
	}

	/**
	 * 批量删除
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "batchDel", method = RequestMethod.POST)
	@ResponseBody
	public Result batchDel(String ids) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			if (StringUtils.isNotBlank(ids)) {
				List<String> idList = new ArrayList<String>();
				if (ids.contains(",")) {
					idList = Arrays.asList(ids.split(","));
				} else {
					idList.add(ids);
				}
				sysRoleService.batchDel(idList);
				roleLinkService.batchDel(idList);
			}
			rs.setMessage("批量删除成功");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("批量删除失败");
		return rf;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "loadRoleTree", method = RequestMethod.GET)
	@ResponseBody
	public List loadRoleTree(){
		List<TSysRole> roleList = new ArrayList<TSysRole>();
		List<Map<String,Object>> lists = new ArrayList<Map<String,Object>>();
		try {
			roleList = sysRoleService.findAll();
			for (TSysRole role : roleList) {
				Map<String,Object> maps = new HashMap<String,Object>();
				maps.put("id", role.getId());
				maps.put("text", role.getName());
				lists.add(maps);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return lists;
	}
}
